﻿using SiMay.Sockets.Tcp;
using SyncFileCommon.BLL;
using SyncFileCommon.Class;
using SyncFileCommon.Model;

namespace SyncFileOption
{
    public partial class FrmSyncPlan : Form
    {

        SyncFileCommon.BLL.ClientBLL TcpClient;

        Action UserLogin;

        /// <summary>
        /// 是否添加信息窗体
        /// </summary>
        public bool IsAdd { get; set; } = true;

        public long ID { get; set; } = 0;

        /// <summary>
        /// 服务器IP
        /// </summary>
        public string ServerIP
        {
            get
            {
                return txtIP.Text;
            }
            set
            {
                txtIP.Text = value;
            }
        }

        /// <summary>
        /// 服务器端口
        /// </summary>
        public int ServerPort
        {
            get
            {
                return Convert.ToInt32(txtPort.Text);
            }
            set
            {
                txtPort.Text = Convert.ToString(value);
            }
        }

        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName
        {
            get
            {
                return txtUserName.Text;
            }
            set
            {
                txtUserName.Text = value;
            }
        }

        /// <summary>
        /// 用户密码
        /// </summary>
        public string Password
        {
            get
            {
                return txtPassword.Text;
            }
            set
            {
                txtPassword.Text = value;
            }
        }

        /// <summary>
        /// 同步目录路径
        /// </summary>
        public string DirPath
        {
            get
            {
                return txtDir.Text;
            }
            set
            {
                txtDir.Text = value;
            }
        }

        /// <summary>
        /// 保存文件路径
        /// </summary>
        public string SaveDirPath
        {
            get
            {
                return txtSaveDirPath.Text;
            }
            set
            {
                txtSaveDirPath.Text = value;
            }
        }

        /// <summary>
        /// 同步计划开始时间
        /// </summary>
        public DateTime BeginTime
        {
            get
            {
                return Convert.ToDateTime(dtpBeginDate.Value.ToString("yyyy-MM-dd") + " " + dtpBeginTime.Value.ToString("HH:mm:ss"));
            }
            set
            {
                if (value < dtpBeginDate.MinDate)
                {
                    dtpBeginDate.Value = Convert.ToDateTime("1799-01-01 00:00:00");
                }
                else
                {
                    dtpBeginDate.Value = value;
                }
                if (value < dtpBeginTime.MinDate)
                {
                    dtpBeginTime.Value = Convert.ToDateTime("1799-01-01 00:00:00");
                }
                else
                {
                    dtpBeginTime.Value = value;
                }

            }
        }

        /// <summary>
        /// 同步计划结束时间
        /// </summary>
        public DateTime EndTime
        {
            get
            {
                return Convert.ToDateTime(dtpEndDate.Value.ToString("yyyy-MM-dd") + " " + dtpEndTime.Value.ToString("HH:mm:ss"));
            }
            set
            {
                if (value < dtpEndDate.MinDate)
                {
                    dtpEndDate.Value = Convert.ToDateTime("1799-01-01 00:00:00");
                }
                else
                {
                    dtpEndDate.Value = value;
                }
                if (value < dtpEndTime.MinDate)
                {
                    dtpEndTime.Value = Convert.ToDateTime("1799-01-01 00:00:00");
                }
                else
                {
                    dtpEndTime.Value = value;
                }

            }
        }

        /// <summary>
        /// 运行间隔类型 O，只执行一次 R，固定间隔循环执行  E，执行结束后间隔再执行
        /// </summary>
        public string RunType
        {
            get
            {
                if (cboxRunType.SelectedIndex == 0)
                {
                    return "O";
                }
                if (cboxRunType.SelectedIndex == 1)
                {
                    return "R";
                }
                if (cboxRunType.SelectedIndex == 2)
                {
                    return "E";
                }
                return "O";
            }
            set
            {
                if (value == "O")
                {
                    cboxRunType.SelectedIndex = 0;
                }
                if (value == "R")
                {
                    cboxRunType.SelectedIndex = 1;
                }
                if (value == "E")
                {
                    cboxRunType.SelectedIndex = 2;
                }

            }
        }

        /// <summary>
        /// 运行间隔时间(秒)
        /// </summary>
        public int IntervalTime
        {
            get
            {
                int _intervalTime = 0;
                if (Convert.ToInt32(txtIntervalTimeD.Text) > 0)
                {
                    _intervalTime = _intervalTime + Convert.ToInt32(txtIntervalTimeD.Text) * (60 * 60 * 24);
                }
                if (Convert.ToInt32(txtIntervalTimeH.Text) > 0)
                {
                    _intervalTime = _intervalTime + Convert.ToInt32(txtIntervalTimeH.Text) * (60 * 60);
                }
                if (Convert.ToInt32(txtIntervalTimeM.Text) > 0)
                {
                    _intervalTime = _intervalTime + Convert.ToInt32(txtIntervalTimeM.Text) * (60);
                }
                if (Convert.ToInt32(txtIntervalTimeS.Text) > 0)
                {
                    _intervalTime = _intervalTime + Convert.ToInt32(txtIntervalTimeS.Text);
                }
                return _intervalTime;
            }
            set
            {
                int _intervalTime = value;
                if (_intervalTime >= (60 * 60 * 24))
                {
                    int quotientD = Math.DivRem(_intervalTime, (60 * 60 * 24), out _intervalTime);
                    if (quotientD > 0)
                    {
                        txtIntervalTimeD.Text = quotientD.ToString();
                    }
                }
                else
                {
                    txtIntervalTimeD.Text = "0";
                }
                if (_intervalTime >= (60 * 60))
                {
                    int quotientH = Math.DivRem(_intervalTime, (60 * 60), out _intervalTime);
                    if (quotientH > 0)
                    {
                        txtIntervalTimeH.Text = quotientH.ToString();
                    }
                }
                else
                {
                    txtIntervalTimeH.Text = "0";
                }
                if (_intervalTime >= (60))
                {
                    int quotientM = Math.DivRem(_intervalTime, (60), out _intervalTime);
                    if (quotientM > 0)
                    {
                        txtIntervalTimeM.Text = quotientM.ToString();
                    }
                }
                else
                {
                    txtIntervalTimeM.Text = "0";
                }
                if (_intervalTime > 0)
                {
                    txtIntervalTimeS.Text = _intervalTime.ToString();
                }
                else
                {
                    txtIntervalTimeS.Text = "0";
                }
            }
        }

        /// <summary>
        /// 任务状态  1，启用  0，停止
        /// </summary>
        public int State
        {
            get
            {
                if (chboxIsStop.Checked)
                {
                    return 0;
                }
                else
                { return 1; }
            }
            set
            {
                if (value == 0)
                {
                    chboxIsStop.Checked = true;
                }
                else
                {
                    chboxIsStop.Checked = false;
                }
            }
        }


        public FrmSyncPlan()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;//设置边框为不可调节
            this.MaximizeBox = false; //取消最大化按键
            this.MinimizeBox = false; //取消最小化按键
            this.ShowInTaskbar = false;//不在任务栏显示多个窗体框
        }


        private void FrmSyncPlan_Load(object sender, EventArgs e)
        {
            dtpBeginTime.Format = DateTimePickerFormat.Time;
            dtpBeginTime.ShowUpDown = true;
            dtpEndTime.Format = DateTimePickerFormat.Time;
            dtpEndTime.ShowUpDown = true;
            if (this.IsAdd)
            {
                dtpBeginDate.Value = DateTime.Now;
                dtpEndDate.Value = DateTime.Now;
                dtpBeginTime.Value = Convert.ToDateTime("2000-01-01 00:00:00");
                dtpEndTime.Value = Convert.ToDateTime("2000-01-01 23:59:59");
            }
            else
            {
                btnRun.Visible = true;
            }
            txtIP.Focus();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {

            if (string.IsNullOrWhiteSpace(txtIP.Text))
            {
                MessageBox.Show(this, "请输入服务器IP", "提示");
                txtDir.Focus();
                return;
            }

            if (string.IsNullOrWhiteSpace(txtPort.Text))
            {
                MessageBox.Show(this, "请输入服务器端口号", "提示");
                txtPort.Focus();
                return;
            }

            if (string.IsNullOrWhiteSpace(txtUserName.Text))
            {
                MessageBox.Show(this, "请输入登录用户名", "提示");
                txtUserName.Focus();
                return;
            }

            if (string.IsNullOrWhiteSpace(txtPassword.Text))
            {
                MessageBox.Show(this, "请输入登录密码", "提示");
                txtPassword.Focus();
                return;
            }

            TcpClient = new SyncFileCommon.BLL.ClientBLL();
            UserLogin = () =>
            {
                txtIP.ReadOnly = true;
                txtPort.ReadOnly = true;
                txtUserName.ReadOnly = true;
                txtPassword.ReadOnly = true;

                JsonHelper _json = new JsonHelper();
                _json.AddVar("MessageType", "UserLogin");
                _json.AddVar("UserName", txtUserName.Text.Trim());
                _json.AddVar("Password", txtPassword.Text.Trim());
                SessionHelper.SendData(TcpClient.Session, MessageHelper.CopyMessageHeadTo(MessageHead.JsonString, _json.JsonStr));
            };
            TcpClient.ClientEvent += Client_ClientEvent;
            if (TcpClient.ClientConnect(this.txtIP.Text, Convert.ToInt32(this.txtPort.Text)))
            { 
                
                
            }
            else
            {
                MessageBox.Show(this, "连接服务器失败", "提示");
            }

        }



        private void Client_ClientEvent(TcpSocketCompletionNotify e, SiMay.Sockets.Tcp.Session.TcpSocketSaeaSession session)
        {
            switch (e)
            {
                case TcpSocketCompletionNotify.OnConnected:
                    UserLogin?.Invoke();
                    break;
                case TcpSocketCompletionNotify.OnConnectedError:
                    MessageBox.Show(this, "连接服务器失败", "提示");
                    break;
                case TcpSocketCompletionNotify.OnSend:

                    //session发送数据通知事件
                    //session.SendTransferredBytes == 以发送数据长度

                    break;
                case TcpSocketCompletionNotify.OnDataReceiveing:

                    break;
                case TcpSocketCompletionNotify.OnDataReceived:
                    byte[] pack = session.CompletedBuffer;//完整数据包
                    var _rd = SessionHelper.RecieverData(session, pack, null);

                    if (new SessionHelper.DataPackType[] { SessionHelper.DataPackType.DataOnePack, SessionHelper.DataPackType.DataMultiplePack, SessionHelper.DataPackType.FileDataPack }.Contains(_rd.PackType))
                    {
                        if (_rd.DataAllLength == _rd.RedeiverLength)
                        {
                            switch (MessageHelper.GetMessageHead<MessageHead>(_rd.Data))
                            {
                                case MessageHead.JsonString:
                                    {
                                        string _s = MessageHelper.GetMessageStringData(_rd.Data);
                                        JsonHelper _json = new JsonHelper(_s);
                                        string _messageType = _json.GetVar("MessageType");
                                        switch (_messageType)
                                        {
                                            case "LoginOK":
                                                {
                                                    if (session.AppTokens == null)
                                                    {
                                                        session.AppTokens = new System.Collections.Concurrent.ConcurrentDictionary<string, object>();
                                                    }
                                                    session.AppTokens.AddOrUpdate("LoginState", "OK", (key, oldValue) => { return "OK"; });
                                                    Task.Run(() =>
                                                    {
                                                        btnLogin.Invoke(new Action(() =>
                                                        {
                                                            btnLogin.Visible = false;
                                                        }));

                                                        btnShowSelectDir.Invoke(new Action(() =>
                                                        {
                                                            btnShowSelectDir.Visible = true;
                                                        }));

                                                    });
                                                    break;
                                                }
                                            case "LoginFail":
                                                {
                                                    MessageBox.Show(this, "用户名或密码错误", "提示");

                                                    break;
                                                }

                                            case "SubDirectoryInfo":
                                                {
                                                    string _data = _json.GetVar("Data");
                                                    List<string> _dirPathList = JsonHelper.GetObjectFromJsonStr<List<string>>(_data);
                                                    foreach (string _dirPath in _dirPathList)
                                                    {

                                                        Task.Run(() =>
                                                        {
                                                            treeDir.Invoke(new Action(() =>
                                                            {
                                                                if (treeDir.SelectedNode == null)
                                                                {
                                                                    TreeNode _tn = treeDir.Nodes.Add(_dirPath);
                                                                    _tn.Tag = _dirPath;
                                                                    pnlSelectDir.Visible = true;
                                                                }
                                                                else
                                                                {
                                                                    string _fDirPath = Convert.ToString(treeDir.SelectedNode.Tag);
                                                                    if (_fDirPath.Substring(_fDirPath.Length - 1) != @"\")
                                                                    {
                                                                        _fDirPath = _fDirPath + @"\";
                                                                    }
                                                                    TreeNode _tn = treeDir.SelectedNode.Nodes.Add(_dirPath.Replace(_fDirPath, ""));
                                                                    _tn.Tag = _dirPath;
                                                                    treeDir.SelectedNode.ExpandAll();
                                                                }

                                                            }));
                                                        });
                                                    }

                                                    break;
                                                }
                                        }

                                        break;
                                    }

                            }
                        }
                    }

                    break;
                case TcpSocketCompletionNotify.OnClosed:
                    Task.Run(() =>
                    {
                        btnLogin.Invoke(new Action(() =>
                        {
                            btnLogin.Visible = true;
                        }));
                        txtIP.Invoke(new Action(() =>
                        {
                            txtIP.ReadOnly = false;
                        }));
                        txtPort.Invoke(new Action(() =>
                        {
                            txtPort.ReadOnly = false;
                        }));
                        txtUserName.Invoke(new Action(() =>
                        {
                            txtUserName.ReadOnly = false;
                        }));
                        txtPassword.Invoke(new Action(() =>
                        {
                            txtPassword.ReadOnly = false;
                        }));


                        btnShowSelectDir.Invoke(new Action(() =>
                        {
                            btnShowSelectDir.Visible = false;
                        }));

                    });
                    break;
            }
        }

        private void btnShowSelectDir_Click(object sender, EventArgs e)
        {
            if (TcpClient.Session == null)
            {
                MessageBox.Show(this, "请先登录服务器", "提示");
                return;
            }
            if (TcpClient.Session.AppTokens == null)
            {
                MessageBox.Show(this, "请先登录服务器", "提示");
                return;
            }

            if (!TcpClient.Session.AppTokens.ContainsKey("LoginState"))
            {
                MessageBox.Show(this, "请先登录服务器", "提示");
                return;
            }
            if (Convert.ToString(TcpClient.Session.AppTokens.GetValueOrDefault("LoginState")) != "OK")
            {
                MessageBox.Show(this, "请先登录服务器", "提示");
                return;
            }

            treeDir.Nodes.Clear();

            JsonHelper _json = new JsonHelper();
            _json.AddVar("MessageType", "GetDirSubDirectory");
            _json.AddVar("DirPath", "");
            SessionHelper.SendData(TcpClient.Session, MessageHelper.CopyMessageHeadTo(MessageHead.JsonString, _json.JsonStr));


            pnlSelectDir.Left = txtDir.Left;

            pnlSelectDir.Top = txtDir.Top + txtDir.Height + 10;

        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void treeDir_DoubleClick(object sender, EventArgs e)
        {
            if (TcpClient.Session == null)
            {
                MessageBox.Show(this, "请先登录服务器", "提示");
                return;
            }
            if (TcpClient.Session.AppTokens == null)
            {
                MessageBox.Show(this, "请先登录服务器", "提示");
                return;
            }

            if (!TcpClient.Session.AppTokens.ContainsKey("LoginState"))
            {
                MessageBox.Show(this, "请先登录服务器", "提示");
                return;
            }
            if (Convert.ToString(TcpClient.Session.AppTokens.GetValueOrDefault("LoginState")) != "OK")
            {
                MessageBox.Show(this, "请先登录服务器", "提示");
                return;
            }

            // 确保有选中的节点
            if (treeDir.SelectedNode != null)
            {
                if (treeDir.SelectedNode.Nodes.Count == 0)
                {
                    JsonHelper _json = new JsonHelper();
                    _json.AddVar("MessageType", "GetDirSubDirectory");
                    _json.AddVar("DirPath", treeDir.SelectedNode.Tag);
                    SessionHelper.SendData(TcpClient.Session, MessageHelper.CopyMessageHeadTo(MessageHead.JsonString, _json.JsonStr));
                }

            }
        }

        private void btnSelectDir_Click(object sender, EventArgs e)
        {
            if (treeDir.SelectedNode != null)
            {
                txtDir.Text = Convert.ToString(treeDir.SelectedNode.Tag);
                pnlSelectDir.Visible = false;
            }
            else
            {
                MessageBox.Show(this, "请选择文件夹", "提示");
            }
        }

        private void btnCloseSelectDir_Click(object sender, EventArgs e)
        {
            pnlSelectDir.Visible = false;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtIP.Text))
            {
                MessageBox.Show("请输入IP地址");
                txtIP.Focus();
                return;
            }
            if (string.IsNullOrWhiteSpace(txtDir.Text))
            {
                MessageBox.Show("同步文件夹路径不可为空");
                txtDir.Focus();
                return;
            }
            if (string.IsNullOrWhiteSpace(txtSaveDirPath.Text))
            {
                MessageBox.Show("保存文件夹路径不可为空");
                txtSaveDirPath.Focus();
                return;
            }

            if (string.IsNullOrWhiteSpace(txtIntervalTimeS.Text) && string.IsNullOrWhiteSpace(txtIntervalTimeM.Text) && string.IsNullOrWhiteSpace(txtIntervalTimeH.Text) && string.IsNullOrWhiteSpace(txtIntervalTimeD.Text))
            {
                MessageBox.Show("请输入执行间隔时间");
                txtIntervalTimeS.Focus();
                return;
            }
            if (string.IsNullOrWhiteSpace(txtIntervalTimeS.Text))
            {
                txtIntervalTimeS.Text = "";
            }
            if (string.IsNullOrWhiteSpace(txtIntervalTimeM.Text))
            {
                txtIntervalTimeM.Text = "";
            }
            if (string.IsNullOrWhiteSpace(txtIntervalTimeH.Text))
            {
                txtIntervalTimeH.Text = "";
            }
            if (string.IsNullOrWhiteSpace(txtIntervalTimeD.Text))
            {
                txtIntervalTimeD.Text = "";
            }

            this.DialogResult = DialogResult.OK;
        }

        private void btnSaveDirPath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
            folderBrowser.SelectedPath = "";
            folderBrowser.Description = "请选择保存文件的文件夹";
            folderBrowser.ShowNewFolderButton = true;//是否显示新建文件夹按钮
            if (folderBrowser.ShowDialog() == DialogResult.OK)
            {
                this.txtSaveDirPath.Text = folderBrowser.SelectedPath;
            }
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(this, "是否立即执行同步计划", "提示",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                SyncPlanBLL.SyncServerFile(ID);
            }
        }
    }
}
